<template>
  <div class="task-list">
    <!-- 头部操作栏 -->
    <div class="task-header">
      <div class="task-title">
        <h3>转换任务</h3>
        <span class="task-count">{{ filteredTasks.length }} 个任务</span>
      </div>
      
      <div class="task-actions">
        <!-- 状态筛选 -->
        <select v-model="statusFilter" class="status-filter">
          <option value="">全部状态</option>
          <option value="queued">排队中</option>
          <option value="processing">处理中</option>
          <option value="completed">已完成</option>
          <option value="failed">失败</option>
          <option value="cancelled">已取消</option>
        </select>
        
        <!-- 刷新按钮 -->
        <button
          class="refresh-btn"
          @click="refreshTasks"
          :disabled="isLoading"
          title="刷新任务列表"
        >
          <svg
            width="20"
            height="20"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            :class="{ 'spinning': isLoading }"
          >
            <polyline points="23 4 23 10 17 10"/>
            <polyline points="1 20 1 14 7 14"/>
            <path d="m20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15"/>
          </svg>
        </button>
        
        <!-- 批量操作 -->
        <div v-if="selectedTasks.length > 0" class="batch-actions">
          <button
            class="batch-btn cancel"
            @click="batchCancel"
            :disabled="isBatchProcessing"
          >
            取消选中 ({{ selectedTasks.length }})
          </button>
          <button
            class="batch-btn delete"
            @click="batchDelete"
            :disabled="isBatchProcessing"
          >
            删除选中 ({{ selectedTasks.length }})
          </button>
        </div>
      </div>
    </div>
    
    <!-- 任务列表 -->
    <div class="task-content">
      <!-- 加载状态 -->
      <div v-if="isLoading && tasks.length === 0" class="loading-state">
        <div class="loading-spinner">
          <div class="spinner"></div>
        </div>
        <p>加载任务列表...</p>
      </div>
      
      <!-- 空状态 -->
      <div v-else-if="filteredTasks.length === 0" class="empty-state">
        <div class="empty-icon">
          <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1">
            <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
            <polyline points="14,2 14,8 20,8"/>
            <line x1="16" y1="13" x2="8" y2="13"/>
            <line x1="16" y1="17" x2="8" y2="17"/>
            <polyline points="10,9 9,9 8,9"/>
          </svg>
        </div>
        <h4>{{ statusFilter ? '没有符合条件的任务' : '暂无转换任务' }}</h4>
        <p>{{ statusFilter ? '尝试更改筛选条件' : '上传文件开始转换' }}</p>
      </div>
      
      <!-- 任务项 -->
      <div v-else class="task-items">
        <div
          v-for="task in paginatedTasks"
          :key="task.id"
          class="task-item"
          :class="{
            'selected': selectedTasks.includes(task.id),
            'processing': task.status === 'processing',
            'completed': task.status === 'completed',
            'failed': task.status === 'failed'
          }"
        >
          <!-- 选择框 -->
          <div class="task-checkbox">
            <input
              type="checkbox"
              :value="task.id"
              v-model="selectedTasks"
              :disabled="task.status === 'processing'"
            />
          </div>
          
          <!-- 任务信息 -->
          <div class="task-info">
            <div class="task-main">
              <div class="task-file">
                <div class="file-icon">
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                    <polyline points="14,2 14,8 20,8"/>
                  </svg>
                </div>
                <div class="file-details">
                  <span class="file-name">{{ task.filename }}</span>
                  <span class="file-format">转换为 {{ task.output_format?.toUpperCase() }}</span>
                </div>
              </div>
              
              <div class="task-status">
                <span class="status-badge" :class="task.status">
                  {{ getStatusText(task.status) }}
                </span>
                <span class="task-time">{{ formatTime(task.created_at) }}</span>
              </div>
            </div>
            
            <!-- 进度条 -->
            <div v-if="task.status === 'processing'" class="task-progress">
              <div class="progress-bar">
                <div
                  class="progress-fill"
                  :style="{ width: task.progress + '%' }"
                ></div>
              </div>
              <span class="progress-text">{{ task.progress }}%</span>
            </div>
            
            <!-- 错误信息 -->
            <div v-if="task.status === 'failed' && task.error_message" class="task-error">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <circle cx="12" cy="12" r="10"/>
                <line x1="15" y1="9" x2="9" y2="15"/>
                <line x1="9" y1="9" x2="15" y2="15"/>
              </svg>
              <span>{{ task.error_message }}</span>
            </div>
          </div>
          
          <!-- 操作按钮 -->
          <div class="task-actions">
            <!-- 下载按钮 -->
            <button
              v-if="task.status === 'completed'"
              class="action-btn download"
              @click="downloadTask(task)"
              title="下载文件"
            >
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                <polyline points="7,10 12,15 17,10"/>
                <line x1="12" y1="15" x2="12" y2="3"/>
              </svg>
            </button>
            
            <!-- 重试按钮 -->
            <button
              v-if="task.status === 'failed' || task.status === 'cancelled'"
              class="action-btn retry"
              @click="retryTask(task)"
              title="重新转换"
            >
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polyline points="23 4 23 10 17 10"/>
                <polyline points="1 20 1 14 7 14"/>
                <path d="m20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15"/>
              </svg>
            </button>
            
            <!-- 取消按钮 -->
            <button
              v-if="task.status === 'queued' || task.status === 'processing'"
              class="action-btn cancel"
              @click="cancelTask(task)"
              title="取消任务"
            >
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <line x1="18" y1="6" x2="6" y2="18"/>
                <line x1="6" y1="6" x2="18" y2="18"/>
              </svg>
            </button>
            
            <!-- 删除按钮 -->
            <button
              v-if="task.status !== 'processing'"
              class="action-btn delete"
              @click="deleteTask(task)"
              title="删除任务"
            >
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polyline points="3,6 5,6 21,6"/>
                <path d="m19,6v14a2,2 0 0,1 -2,2H7a2,2 0 0,1 -2,-2V6m3,0V4a2,2 0 0,1 2,-2h4a2,2 0 0,1 2,2v2"/>
              </svg>
            </button>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div v-if="totalPages > 1" class="pagination">
        <button
          class="page-btn"
          @click="currentPage = 1"
          :disabled="currentPage === 1"
        >
          首页
        </button>
        <button
          class="page-btn"
          @click="currentPage--"
          :disabled="currentPage === 1"
        >
          上一页
        </button>
        
        <div class="page-numbers">
          <button
            v-for="page in visiblePages"
            :key="page"
            class="page-btn"
            :class="{ active: page === currentPage }"
            @click="currentPage = page"
          >
            {{ page }}
          </button>
        </div>
        
        <button
          class="page-btn"
          @click="currentPage++"
          :disabled="currentPage === totalPages"
        >
          下一页
        </button>
        <button
          class="page-btn"
          @click="currentPage = totalPages"
          :disabled="currentPage === totalPages"
        >
          末页
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useTaskStore } from '@/stores/task'
import { apiService } from '@/services/api'
import type { Task } from '@/types'

interface Props {
  autoRefresh?: boolean
  refreshInterval?: number
  pageSize?: number
}

const props = withDefaults(defineProps<Props>(), {
  autoRefresh: true,
  refreshInterval: 5000,
  pageSize: 10
})

const emit = defineEmits<{
  taskClick: [task: Task]
  download: [task: Task]
}>()

// 响应式数据
const taskStore = useTaskStore()
const isLoading = ref(false)
const isBatchProcessing = ref(false)
const statusFilter = ref('')
const selectedTasks = ref<string[]>([])
const currentPage = ref(1)
const refreshTimer = ref<NodeJS.Timeout>()

// 计算属性
const tasks = computed(() => taskStore.tasks)

const filteredTasks = computed(() => {
  if (!statusFilter.value) return tasks.value
  return tasks.value.filter(task => task.status === statusFilter.value)
})

const totalPages = computed(() => {
  return Math.ceil(filteredTasks.value.length / props.pageSize)
})

const paginatedTasks = computed(() => {
  const start = (currentPage.value - 1) * props.pageSize
  const end = start + props.pageSize
  return filteredTasks.value.slice(start, end)
})

const visiblePages = computed(() => {
  const pages = []
  const total = totalPages.value
  const current = currentPage.value
  
  if (total <= 7) {
    for (let i = 1; i <= total; i++) {
      pages.push(i)
    }
  } else {
    if (current <= 4) {
      for (let i = 1; i <= 5; i++) {
        pages.push(i)
      }
      pages.push('...', total)
    } else if (current >= total - 3) {
      pages.push(1, '...')
      for (let i = total - 4; i <= total; i++) {
        pages.push(i)
      }
    } else {
      pages.push(1, '...')
      for (let i = current - 1; i <= current + 1; i++) {
        pages.push(i)
      }
      pages.push('...', total)
    }
  }
  
  return pages
})

// 生命周期
onMounted(() => {
  refreshTasks()
  if (props.autoRefresh) {
    startAutoRefresh()
  }
})

onUnmounted(() => {
  stopAutoRefresh()
})

// 监听筛选条件变化，重置页码
watch(statusFilter, () => {
  currentPage.value = 1
})

// 方法
const refreshTasks = async () => {
  isLoading.value = true
  try {
    await taskStore.fetchTasks()
  } catch (error) {
    console.error('刷新任务列表失败:', error)
  } finally {
    isLoading.value = false
  }
}

const startAutoRefresh = () => {
  refreshTimer.value = setInterval(() => {
    refreshTasks()
  }, props.refreshInterval)
}

const stopAutoRefresh = () => {
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value)
    refreshTimer.value = undefined
  }
}

const downloadTask = async (task: Task) => {
  try {
    const response = await apiService.get(`/download/${task.id}`, {
      responseType: 'blob'
    })
    
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.download = `${task.filename}.${task.output_format}`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    emit('download', task)
  } catch (error) {
    console.error('下载失败:', error)
  }
}

const retryTask = async (task: Task) => {
  try {
    await apiService.post(`/tasks/${task.id}/retry`)
    await refreshTasks()
  } catch (error) {
    console.error('重试任务失败:', error)
  }
}

const cancelTask = async (task: Task) => {
  try {
    await apiService.post(`/tasks/${task.id}/cancel`)
    await refreshTasks()
  } catch (error) {
    console.error('取消任务失败:', error)
  }
}

const deleteTask = async (task: Task) => {
  if (!confirm(`确定要删除任务 "${task.filename}" 吗？`)) {
    return
  }
  
  try {
    await apiService.delete(`/tasks/${task.id}`)
    await refreshTasks()
  } catch (error) {
    console.error('删除任务失败:', error)
  }
}

const batchCancel = async () => {
  if (!confirm(`确定要取消选中的 ${selectedTasks.value.length} 个任务吗？`)) {
    return
  }
  
  isBatchProcessing.value = true
  try {
    await apiService.post('/tasks/batch', {
      action: 'cancel',
      task_ids: selectedTasks.value
    })
    selectedTasks.value = []
    await refreshTasks()
  } catch (error) {
    console.error('批量取消失败:', error)
  } finally {
    isBatchProcessing.value = false
  }
}

const batchDelete = async () => {
  if (!confirm(`确定要删除选中的 ${selectedTasks.value.length} 个任务吗？`)) {
    return
  }
  
  isBatchProcessing.value = true
  try {
    await apiService.post('/tasks/batch', {
      action: 'delete',
      task_ids: selectedTasks.value
    })
    selectedTasks.value = []
    await refreshTasks()
  } catch (error) {
    console.error('批量删除失败:', error)
  } finally {
    isBatchProcessing.value = false
  }
}

const getStatusText = (status: string): string => {
  const statusMap: Record<string, string> = {
    queued: '排队中',
    processing: '处理中',
    completed: '已完成',
    failed: '失败',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

const formatTime = (dateString: string): string => {
  const date = new Date(dateString)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)
  
  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`
  
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
.task-list {
  width: 100%;
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  flex-wrap: wrap;
  gap: 16px;
}

.task-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.task-title h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #374151;
}

.task-count {
  padding: 4px 8px;
  background: #f3f4f6;
  border-radius: 12px;
  font-size: 12px;
  color: #6b7280;
}

.task-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.status-filter {
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  background: white;
}

.refresh-btn {
  padding: 8px;
  background: white;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.refresh-btn:hover {
  background: #f9fafb;
}

.refresh-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.spinning {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.batch-actions {
  display: flex;
  gap: 8px;
}

.batch-btn {
  padding: 8px 12px;
  border: none;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.batch-btn.cancel {
  background: #fef3c7;
  color: #d97706;
}

.batch-btn.cancel:hover {
  background: #fde68a;
}

.batch-btn.delete {
  background: #fecaca;
  color: #dc2626;
}

.batch-btn.delete:hover {
  background: #fca5a5;
}

.task-content {
  background: white;
  border-radius: 12px;
  border: 1px solid #e5e7eb;
  overflow: hidden;
}

.loading-state,
.empty-state {
  padding: 60px 20px;
  text-align: center;
  color: #6b7280;
}

.loading-spinner {
  display: flex;
  justify-content: center;
  margin-bottom: 16px;
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #e5e7eb;
  border-top: 3px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.empty-icon {
  margin-bottom: 16px;
  color: #d1d5db;
}

.empty-state h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 500;
  color: #374151;
}

.empty-state p {
  margin: 0;
  font-size: 14px;
}

.task-items {
  display: flex;
  flex-direction: column;
}

.task-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px 20px;
  border-bottom: 1px solid #f3f4f6;
  transition: all 0.2s ease;
}

.task-item:last-child {
  border-bottom: none;
}

.task-item:hover {
  background: #f9fafb;
}

.task-item.selected {
  background: #eff6ff;
  border-color: #dbeafe;
}

.task-item.processing {
  background: #f0fdf4;
}

.task-item.completed {
  background: #f0f9ff;
}

.task-item.failed {
  background: #fef2f2;
}

.task-checkbox input[type="checkbox"] {
  width: 16px;
  height: 16px;
  margin: 0;
}

.task-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.task-main {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
}

.task-file {
  display: flex;
  align-items: center;
  gap: 12px;
}

.file-icon {
  color: #6b7280;
}

.file-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.file-name {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

.file-format {
  font-size: 12px;
  color: #6b7280;
}

.task-status {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.queued {
  background: #fef3c7;
  color: #d97706;
}

.status-badge.processing {
  background: #dbeafe;
  color: #2563eb;
}

.status-badge.completed {
  background: #d1fae5;
  color: #059669;
}

.status-badge.failed {
  background: #fecaca;
  color: #dc2626;
}

.status-badge.cancelled {
  background: #f3f4f6;
  color: #6b7280;
}

.task-time {
  font-size: 12px;
  color: #9ca3af;
}

.task-progress {
  display: flex;
  align-items: center;
  gap: 12px;
}

.progress-bar {
  flex: 1;
  height: 6px;
  background: #e5e7eb;
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #3b82f6, #10b981);
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 12px;
  color: #6b7280;
  min-width: 32px;
}

.task-error {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
  background: #fef2f2;
  border: 1px solid #fecaca;
  border-radius: 6px;
  color: #dc2626;
  font-size: 12px;
}

.task-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  padding: 8px;
  background: none;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  color: #6b7280;
}

.action-btn:hover {
  background: #f9fafb;
}

.action-btn.download {
  color: #059669;
  border-color: #d1fae5;
}

.action-btn.download:hover {
  background: #d1fae5;
}

.action-btn.retry {
  color: #2563eb;
  border-color: #dbeafe;
}

.action-btn.retry:hover {
  background: #dbeafe;
}

.action-btn.cancel {
  color: #d97706;
  border-color: #fef3c7;
}

.action-btn.cancel:hover {
  background: #fef3c7;
}

.action-btn.delete {
  color: #dc2626;
  border-color: #fecaca;
}

.action-btn.delete:hover {
  background: #fecaca;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  padding: 20px;
  border-top: 1px solid #f3f4f6;
}

.page-btn {
  padding: 8px 12px;
  background: white;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.page-btn:hover:not(:disabled) {
  background: #f9fafb;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-btn.active {
  background: #3b82f6;
  color: white;
  border-color: #3b82f6;
}

.page-numbers {
  display: flex;
  gap: 4px;
}

@media (max-width: 768px) {
  .task-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .task-actions {
    justify-content: space-between;
  }
  
  .task-main {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .task-status {
    align-items: flex-start;
  }
  
  .pagination {
    flex-wrap: wrap;
  }
}
</style>